<template>
  <div class="app-container">
    <div class="app-container-header">
      <div class="app-container-header-text">注：只有同一专业大类下的专业名称可通过拖拽来调整排序</div>
      <div class="app-container-header-btn">
        <el-button :icon="!isClose?'el-icon-circle-plus-outline':'el-icon-remove-outline'" size="mini" @click="handlechange">{{!isClose?'全部展开':'全部收起'}}</el-button>
      </div>
    </div>
    <div class="app-container-table">
      <div class="app-container-table-title">
        <div class="app-container-table-title-box1">
          专业大类
        </div>
        <div class="app-container-table-title-box2">
          专业大类编码
        </div>
        <div class="app-container-table-title-box6">
          操作
        </div>
      </div>
      <div class="app-container-table-content">
        <el-tree
          :data="data"
          node-key="id"
          draggable
          ref="selectTree"
          :expand-on-click-node="true"
          @node-drop="handleDrop"
          :allow-drop="allowDrop">
          <div class="custom-tree-node" slot-scope="{ data }">
            <div v-if="!data.id" class="label">{{ data.majorTypeName}}</div>
            <div v-if="!data.id" class="rank">{{data.majorTypeNum}}</div>
            <div style="margin-left: 16px" v-if="data.id" class="label">{{data.majorName}}</div>
            <div style="margin-left: 16px" v-if="data.id" class="rank">{{data.majorNum}}</div>
            <div class="btn" @click.stop>
              <el-button
                v-if="data.level==2"
                type="text"
                size="mini"
                @click="() => handleEditor(data)">
                编辑
              </el-button>
              <el-button
                v-if="data.level==1"
                type="text"
                size="mini"
                @click="() => handleAdd(data)">
                添加专业名称
              </el-button>
              <el-button
                v-if="data.level==2"
                type="text"
                size="mini"
                @click="() => handleDelete(data)">
                删除
              </el-button>
            </div>
          </div>
        </el-tree>
      </div>
    </div>
    <!-- 添加课程评价回复对话框 -->
    <el-dialog class="order-dialog"
               :title="title"
               :visible.sync="open"
               width="500px"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="专业大类" label-width="120px" prop="major">
          <el-input v-model="form.majorTypeName" disabled/>
        </el-form-item>
        <el-form-item label="专业名称" label-width="120px" prop="majorName">
          <el-input v-model="form.majorName" placeholder="请输入专业名称" />
        </el-form-item>
        <el-form-item label="专业名称编码" label-width="120px" prop="majorNum">
          <el-input v-model="form.majorNum" placeholder="请输入专业名称编码" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMajorNameTree, addMajorName, editMajorName, deleteMajorName, editMajorNameSort } from '@/api/major/major'
import { tranListToTreeData } from '@/utils/util'

export default {
  name: "Major",
  data() {
    return {
      isClose: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        majorTypeName: '',
        majorTypeNum: '',
        majorName:'',
        majorNum:'',
      },
      // 表单校验
      rules: {
        majorName:[
          { required: true, message: "请输入专业名称", trigger: "blur" }
        ],
        majorNum:[
          { required: true, message: "请输入专业名称编码", trigger: "blur" }
        ],
      },
      data: [],
    };
  },
  created() {
    this.getMajorNameTree();
  },
  methods: {
    async getMajorNameTree(){
      let res = await getMajorNameTree()
      const {code,data} = res
      if (code==200){
        let restree=tranListToTreeData(data)
        this.data=restree
      }
    },
    // 取消按钮
    cancel() {
      this.form = {
        majorTypeName: '',
        majorTypeNum: '',
        majorName: '',
        majorNum: ''
      }
      this.$refs['form'].resetFields();
      this.open = false
    },
    /** 新增按钮操作 */
    async handleAdd(data) {
      this.open = true
      this.title = '添加专业名称'
      this.form.majorTypeName = data.majorTypeName
      this.form.majorTypeNum = data.majorTypeNum
    },
    /** 编辑操作 */
    async handleEditor(data){
      this.open = true
      this.title = '编辑专业名称'
      this.form.majorTypeName = data.majorTypeName
      this.form.id = data.id
      this.form.majorTypeNum = data.majorTypeNum
      this.form.majorName = data.majorName
      this.form.majorNum = data.majorNum
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          });
          if (this.title == '添加专业名称'){
            let res = await addMajorName(this.form)
            const {code} = res
            if (code==200){
              loading.close()
              this.$modal.msgSuccess('添加成功！')
              this.cancel()
              this.getMajorNameTree()
            }else {
              loading.close()
            }
          }else {
            let res = await editMajorName(this.form)
            const {code} = res
            if (code==200){
              loading.close()
              this.$modal.msgSuccess('编辑成功！')
              this.cancel()
              this.getMajorNameTree()
            }else {
              loading.close()
            }
          }
        } else {
          return false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id
      this.$confirm(`是否确认删除【${row.majorName}】的数据项？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      }).then(async() => {
        const loading = this.$loading({
          lock: true,
          text: '正在删除...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });
        let res = await deleteMajorName(ids)
        if (res.code==200){
          loading.close()
          this.$message.success('操作成功');
          this.getMajorNameTree()
        }else {
          loading.close()
        }
      }).catch(() => {});
    },
    // 转化数列表结构方法
    transformArray(originalArray) {
      return originalArray.map(item => {
        const transformedItem = {
          id: item.id,
          major: item.major,
          createBy: item.createBy,
          createTime: item.createTime,
          status: item.status,
          parentId: item.parentId
        };
        if (item.children.length > 0) {
          transformedItem.children = this.transformArray(item.children);
        }
        return transformedItem
      });
    },
    expandNodes(nodes) {
      nodes.forEach(node => {
        if (node.childNodes) {
          node.expanded = true; // 展开节点
          this.expandNodes(node.childNodes); // 递归展开子节点
        }
      });
    },
    closeNodes(nodes) {
      nodes.forEach(node => {
        if (node.childNodes) {
          node.expanded = false; // 关闭节点
          this.closeNodes(node.childNodes); // 递归关闭子节点
        }
      });
    },
    // 展开关闭操作
    handlechange(){
      this.isClose = !this.isClose
      if(this.isClose){
        this.expandNodes(this.$refs.selectTree.root.childNodes)
      }else{
        this.closeNodes(this.$refs.selectTree.root.childNodes);
      }
    },
    // 拖拽排序
    async handleDrop(draggingNode, dropNode, dropType, ev){
      console.log('tree drop: ', draggingNode, dropNode, dropType, ev);
      let ids = []
      let dropArr=[]
        this.data.forEach(item=>{
          if (item.children.length>0){
            item.children.forEach(childItem=>{
              if (draggingNode.data.id==childItem.id){
                dropArr=item.children
              }
            })
          }
        })
      dropArr.forEach(item=>{
        ids.push(item.id)
      })
      let res = await editMajorNameSort(ids.join(','))
      const {code} = res
      if (code==200){
        this.$modal.msgSuccess('排序成功！')
      }
    },
    //设置子目录可以拖拽
    allowDrop(draggingNode, dropNode, type) {
      //注掉的是同级拖拽
      if (draggingNode.level === dropNode.level) {
        // 获取父节点信息
        const draggingParent = draggingNode.parent;
        const dropParent = dropNode.parent;
        if (draggingNode.level==1){
          return false
        }
        if (draggingParent !== dropParent){
          return false
        }
        return type === 'prev' || type === 'next'
      } else {
        // 不同级进行处理
        return false
      }
    }
  }
};
</script>

<style scoped>
::v-deep .el-tree-node__content {
  padding-left: 0 !important;
  border-bottom: 1px solid #f3f3f3;
  height: 56px;
}
::v-deep.order-dialog .el-dialog {
  border-radius: 15px;
}
::v-deep.order-dialog .el-dialog__title {
  font-weight: 600;
}
</style>

<style lang="scss" scoped>
.app-container{
  &-header{
    display: flex;
    justify-content: space-between;
    &-text{
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #F89A33;
      line-height: 22px;
    }
  }
  &-table{
    margin: 10px 0;
    .table-item{
      display: flex;
      align-items: center;
      &-img{
        width: 118px;
        height: 72px;
        margin: 0 20px;
        border-radius: 5px;
        overflow: hidden;
        img{
          width: 118px;
          height: 72px;
        }
      }
      &-content{
        div{
          color: #999;
        }
      }
    }
    &-title{
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #f3f5f7;
      height: 56px;
      border-top-left-radius: 10px;     /* 左上角 */
      border-top-right-radius: 10px;    /* 右上角 */
      font-weight: 600;
      color: #333333;
      margin-bottom: 10px;
      &-box1{
        text-align: center;
        width: 500px;
        min-width:260px;
      }
      &-box2{
        text-align: center;
        flex: 0.2;
        min-width: 120px;
      }
      &-box3{
        text-align: center;
        flex: 0.2;
        min-width: 120px;
      }
      &-box4{
        text-align: center;
        flex: 0.2;
        min-width: 160px;
      }
      &-box5{
        text-align: center;
        flex: 0.2;
        min-width: 200px;
      }
      &-box6{
        text-align: center;
        flex: 0.2;
        min-width: 200px;
      }
    }
    &-content{
      .el-tree{
        height: calc(100vh - 252px);
        overflow: auto;
      }
      .custom-tree-node{
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
        // border-bottom: 1px solid #f3f3f3;
        .label{
          width: 480px;
          min-width:260px;
          text-align: center;
        }
        .rank{
          flex: 0.2;
          text-align: center;
          min-width: 120px;
        }
        .status{
          flex: 0.2;
          text-align: center;
          min-width: 120px;
        }
        .creator{
          flex: 0.2;
          text-align: center;
          min-width: 160px;
        }
        .createtime{
          flex: 0.2;
          text-align: center;
          min-width: 200px;
        }
        .btn{
          flex: 0.2;
          text-align: center;
          min-width: 200px;
        }
      }
    }
  }
}
</style>
